<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
发送给：<input id="toUser" type="text" />
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script>
    /*<![CDATA[*/
    var nickName = "[[${nickName}]]";
    /*]]>*/
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:7075/websocket/"+nickName);
        // 建立成功后的回调函数
        websocket.onopen = function (ev) {
            setMessageInnerHTML("open");
        }
        websocket.onclose=function(){
            setMessageInnerHTML("close");
        }
        websocket.onmessage=function (ev) {

            var chatMsg = JSON.parse(ev.data)

            console.log(chatMsg);

            if(chatMsg.type==2){
                setMessageInnerHTML("系统消息："+chatMsg.msg);
            }
            else {
                setMessageInnerHTML(chatMsg.fromUser+"："+chatMsg.msg);

            }
        }
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function(){
            websocket.close();
        }

    }else {
        alert("浏览器不支持");
    }
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){

        //获取输入的文本信息进行发送
        var message = document.getElementById('text').value;
        var toUser = document.getElementById('toUser').value;
        var socketMsg = {msg:message,toUser:toUser};
        if(toUser == ''){
            //群聊.
            socketMsg.type = 0;
        }else{
            //单聊.
            socketMsg.type = 1;
        }
        websocket.send(JSON.stringify(socketMsg));

    }
</script>
</html>